<template>
  <div class="simple-ai-chat">
    <div class="chat-container">
      <div class="messages" ref="messagesRef">
        <div
            v-for="(message, index) in messages"
            :key="index"
            :class="['message', message.role]"
        >
          <div class="message-content">
            {{ message.content }}
          </div>
          <div class="message-time">
            {{ formatTime(message.timestamp) }}
          </div>
        </div>
      </div>

      <div class="input-area">
        <div class="input-row">
          <textarea
              v-model="userInput"
              @keydown.enter.prevent="sendMessage"
              placeholder="输入消息..."
              rows="1"
              ref="inputRef"
          ></textarea>
          <button
              class="send-button"
              @click="sendMessage"
              :disabled="isStreaming || !userInput.trim()"
          >
            <span v-if="!isStreaming">发送</span>
            <span v-else>发送中...</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, onMounted, nextTick} from 'vue'
import {chatAPI} from '../services/api'
import {sendChatMessage} from '../services/api2'

const messagesRef = ref(null)
const inputRef = ref(null)
const userInput = ref('')
const isStreaming = ref(false)
const messages = ref([])

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (messagesRef.value) {
    messagesRef.value.scrollTop = messagesRef.value.scrollHeight
  }
}

// 发送消息
const sendMessage = async () => {
  if (isStreaming.value || !userInput.value.trim()) return

  const messageContent = userInput.value.trim()

  // 添加用户消息
  const userMessage = {
    role: 'user',
    content: messageContent,
    timestamp: new Date()
  }
  messages.value.push(userMessage)

  // 清空输入
  userInput.value = ''
  await scrollToBottom()

  // 添加助手消息占位
  const assistantMessage = {
    role: 'assistant',
    content: '',
    timestamp: new Date()
  }
  messages.value.push(assistantMessage)
  isStreaming.value = true

  try {
    // 使用URLSearchParams发送文本数据
    const params = new URLSearchParams()
    params.append('prompt', messageContent)

    const reader = await sendChatMessage(params)
    const decoder = new TextDecoder('utf-8')
    let accumulatedContent = ''  // 累积内容

    while (true) {
      try {
        const {value, done} = await reader.read()
        if (done) break

        // 累积新内容
        accumulatedContent += decoder.decode(value)

        await nextTick(() => {
          // 更新消息，使用累积的内容
          const updatedMessage = {
            ...assistantMessage,
            content: accumulatedContent
          }
          const lastIndex = messages.value.length - 1
          messages.value.splice(lastIndex, 1, updatedMessage)
        })
        await scrollToBottom()
      } catch (readError) {
        console.error('读取流错误:', readError)
        break
      }
    }
  } catch (error) {
    console.error('发送消息失败:', error)
    assistantMessage.content = '抱歉，发生了错误，请稍后重试。'
  } finally {
    isStreaming.value = false
    await scrollToBottom()
  }
}

// 格式化时间
const formatTime = (date) => {
  return new Date(date).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  // 添加欢迎消息
  messages.value.push({
    role: 'assistant',
    content: '你好！我是AI助手，有什么可以帮你的吗？',
    timestamp: new Date()
  })
})
</script>

<style scoped>
.simple-ai-chat {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.chat-container {
  flex: 1;
  display: flex;
  flex-direction: column;
  max-width: 800px;
  margin: 0 auto;
  width: 100%;
  height: 100%;
  background: white;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 1rem;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.message {
  display: flex;
  flex-direction: column;
  max-width: 80%;
}

.message.user {
  align-self: flex-end;
}

.message.assistant {
  align-self: flex-start;
}

.message-content {
  padding: 0.75rem 1rem;
  border-radius: 1rem;
  word-break: break-word;
}

.message.user .message-content {
  background: #007bff;
  color: white;
  border-bottom-right-radius: 0.25rem;
}

.message.assistant .message-content {
  background: #f1f3f5;
  color: #333;
  border-bottom-left-radius: 0.25rem;
}

.message-time {
  font-size: 0.75rem;
  color: #6c757d;
  margin-top: 0.25rem;
  padding: 0 0.5rem;
}

.input-area {
  padding: 1rem;
  border-top: 1px solid #e9ecef;
  background: white;
}

.input-row {
  display: flex;
  gap: 0.5rem;
  align-items: flex-end;
}

textarea {
  flex: 1;
  resize: none;
  border: 1px solid #ced4da;
  border-radius: 0.5rem;
  padding: 0.75rem;
  font-family: inherit;
  font-size: 1rem;
  line-height: 1.5;
  max-height: 150px;
  outline: none;
  transition: border-color 0.2s;
}

textarea:focus {
  border-color: #007bff;
}

.send-button {
  padding: 0.75rem 1.25rem;
  border: none;
  border-radius: 0.5rem;
  background: #007bff;
  color: white;
  cursor: pointer;
  font-weight: 500;
  transition: background-color 0.2s;
}

.send-button:hover:not(:disabled) {
  background: #0069d9;
}

.send-button:disabled {
  background: #6c757d;
  cursor: not-allowed;
}
</style>